import request from '@/utils/request'

// 菜单接口类型定义
export interface Menu {
  id: number
  parent_id?: number
  name: string
  path: string
  component: string
  redirect?: string
  meta?: {
    title?: string
    icon?: string
    affix?: boolean
    hidden?: boolean
    [key: string]: any
  }
  sort: number
  hidden: boolean
  status: number
  created_at: string
  updated_at: string
  children?: Menu[]
}

// 菜单树结构
export interface MenuTree {
  id: number
  parent_id?: number
  name: string
  path: string
  component: string
  redirect?: string
  meta?: {
    title?: string
    icon?: string
    affix?: boolean
    hidden?: boolean
    [key: string]: any
  }
  sort: number
  hidden: boolean
  children?: MenuTree[]
}

// 创建菜单请求
export interface MenuCreateRequest {
  parent_id?: number
  name: string
  path?: string
  component?: string
  redirect?: string
  meta?: string // JSON字符串
  sort?: number
  hidden?: boolean
  status?: number
}

// 更新菜单请求
export interface MenuUpdateRequest {
  parent_id?: number
  name: string
  path?: string
  component?: string
  redirect?: string
  meta?: string // JSON字符串
  sort?: number
  hidden?: boolean
  status?: number
}

// 菜单列表查询参数
export interface MenuListParams {
  page?: number
  page_size?: number
  keyword?: string
}

// 菜单列表响应
export interface MenuListResponse {
  list: Menu[]
  total: number
  page: number
  page_size: number
}

// 菜单排序数据
export interface MenuSortItem {
  id: number
  sort: number
}

/**
 * 获取菜单列表
 */
export function getMenuList(params?: MenuListParams): Promise<MenuListResponse> {
  return request.get('/menus', { params })
}

/**
 * 获取菜单树
 */
export function getMenuTree(): Promise<Menu[]> {
  return request.get('/menus/tree')
}

/**
 * 获取所有菜单（用于角色分配）
 */
export function getAllMenus(): Promise<Menu[]> {
  return request.get('/menus/all')
}

/**
 * 获取所有菜单树（用于角色分配）
 */
export function getAllMenuTree(): Promise<MenuTree[]> {
  return request.get('/menus/all/tree')
}

/**
 * 获取菜单详情
 */
export function getMenuDetail(id: number): Promise<Menu> {
  return request.get(`/menus/${id}`)
}

/**
 * 创建菜单
 */
export function createMenu(data: MenuCreateRequest): Promise<Menu> {
  return request.post('/menus', data)
}

/**
 * 更新菜单
 */
export function updateMenu(id: number, data: MenuUpdateRequest): Promise<Menu> {
  return request.put(`/menus/${id}`, data)
}

/**
 * 删除菜单
 */
export function deleteMenu(id: number): Promise<{ message: string }> {
  return request.delete(`/menus/${id}`)
}

/**
 * 批量更新菜单排序
 */
export function updateMenuSort(data: MenuSortItem[]): Promise<{ message: string }> {
  return request.put('/menus/sort', data)
}

/**
 * 菜单Meta数据辅助函数
 */
export const MenuMetaHelper = {
  /**
   * 解析Meta JSON字符串
   */
  parseMeta(metaStr?: string): any {
    if (!metaStr) return {}
    try {
      return JSON.parse(metaStr)
    } catch (error) {
      console.error('解析菜单Meta数据失败:', error)
      return {}
    }
  },

  /**
   * 将Meta对象转换为JSON字符串
   */
  stringifyMeta(meta: any): string {
    if (!meta || typeof meta !== 'object') return ''
    try {
      return JSON.stringify(meta)
    } catch (error) {
      console.error('序列化菜单Meta数据失败:', error)
      return ''
    }
  },

  /**
   * 验证Meta JSON格式
   */
  validateMeta(metaStr: string): boolean {
    if (!metaStr) return true
    try {
      JSON.parse(metaStr)
      return true
    } catch (error) {
      return false
    }
  }
}

/**
 * 菜单树辅助函数
 */
export const MenuTreeHelper = {
  /**
   * 将平铺菜单列表转换为树形结构
   */
  buildTree(menus: Menu[]): Menu[] {
    const menuMap = new Map<number, Menu>()
    const rootMenus: Menu[] = []

    // 第一遍：创建映射
    menus.forEach(menu => {
      menuMap.set(menu.id, { ...menu, children: [] })
    })

    // 第二遍：构建树形结构
    menus.forEach(menu => {
      const menuItem = menuMap.get(menu.id)!
      if (menu.parent_id) {
        const parent = menuMap.get(menu.parent_id)
        if (parent) {
          parent.children = parent.children || []
          parent.children.push(menuItem)
        }
      } else {
        rootMenus.push(menuItem)
      }
    })

    return rootMenus
  },

  /**
   * 获取菜单的所有父级ID
   */
  getParentIds(menuId: number, menus: Menu[]): number[] {
    const parentIds: number[] = []
    const menuMap = new Map<number, Menu>()
    
    menus.forEach(menu => {
      menuMap.set(menu.id, menu)
    })

    let currentMenu = menuMap.get(menuId)
    while (currentMenu && currentMenu.parent_id) {
      parentIds.unshift(currentMenu.parent_id)
      currentMenu = menuMap.get(currentMenu.parent_id)
    }

    return parentIds
  },

  /**
   * 获取菜单的所有子级ID
   */
  getChildrenIds(menuId: number, menus: Menu[]): number[] {
    const childrenIds: number[] = []
    
    function findChildren(parentId: number) {
      menus.forEach(menu => {
        if (menu.parent_id === parentId) {
          childrenIds.push(menu.id)
          findChildren(menu.id)
        }
      })
    }

    findChildren(menuId)
    return childrenIds
  }
}
